using Godot;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

public partial class mainscene : Node2D
{
    public List<int> PlayerIDList = new List<int>();

    // Called when the node enters the scene tree for the first time.
    public override void _Ready()
    {
         var peer = new ENetMultiplayerPeer();
        var status = peer.CreateServer(17539, 64);
        if (status == Error.Ok)
        {
            Multiplayer.MultiplayerPeer = peer;
            peer.PeerConnected += Peer_PeerConnected;
            GD.Print("启动成功");
        }
        else
        {
            GD.Print("启动失败");
        }
    }

    // Called every frame. 'delta' is the elapsed time since the previous frame.
    public override void _Process(double delta)
    {
    }

    public void _on_button_pressed()
    {
        var port = int.Parse(GetNode<LineEdit>("VBoxContainer/PortInput").Text);
        var maxCount = int.Parse(GetNode<LineEdit>("VBoxContainer/MaxPlayerInput").Text);

        var peer = new ENetMultiplayerPeer();
        var status = peer.CreateServer(port, maxCount);
        if (status == Error.Ok)
        {
            Multiplayer.MultiplayerPeer = peer;
            peer.PeerConnected += Peer_PeerConnected;
            GD.Print("启动成功");
        }
        else
        {
            GD.Print("启动失败");
        }
    }

    private async void Peer_PeerConnected(long id)
    {
        GD.Print($"有新玩家登录 {id} {(int)id}");

        await Task.Delay(1000);
        GD.Print($"发送id {id} {(int)id}");
        Rpc(nameof(AddNewlyPlayer), (int)id);
        RpcId(id, nameof(AddPreviousPlayers), PlayerIDList.ToArray());
        AddPlayer((int)id);
    }

    private void AddPlayer(int id)
    {
        PlayerIDList.Add(id);
        var player = GD.Load<PackedScene>("res://prefabs/player/player.tscn").Instantiate<player>();
        player.SetMultiplayerAuthority(id);
        player.Name = id.ToString();
        AddChild(player);
    }


    [Rpc(MultiplayerApi.RpcMode.Authority,
        CallLocal = true,
        TransferChannel = 1,
        TransferMode = MultiplayerPeer.TransferModeEnum.Reliable)]
    public void DisplayMessage(string message)
    {

    }

    [Rpc(MultiplayerApi.RpcMode.AnyPeer,
        CallLocal = true,
        TransferChannel = 1,
        TransferMode = MultiplayerPeer.TransferModeEnum.Reliable)]
    public void ClickedByPlayer()
    {

    }

    [Rpc]
    public void AddNewlyPlayer(int newPlayerId)
    {

    }

    [Rpc]
    public void AddPreviousPlayers(int[] playerIds)
    {

    }

}
